package com.metamech.vorpal.handler;

import org.apache.log4j.Logger;

import com.metamech.jabber.ErrorTool;
import com.metamech.jabber.Session;
import com.metamech.jabber.xml.Packet;
import com.metamech.jabber.xml.PacketListener;
import com.metamech.log.Log;
import com.metamech.vorpal.User;
import com.metamech.vorpal.UserIndex;

/**
 * Title:
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author
 * @version 1.0
 */

public class RosterHandler implements PacketListener {
	private static Logger logger=Logger.getLogger(RosterHandler.class);
	UserIndex userIndex;
	public RosterHandler(UserIndex index) { userIndex = index; }

	public void notify(Packet packet) {
		packet.setTo(null);
		packet.setFrom(null);

		if (packet.getSession().getStatus() != Session.AUTHENTICATED){
			logger.info("RosterHandler: Not authenticated" + packet.toString());
			ErrorTool.setError(packet,401,"You must be authenticated to send roster update");
			MessageHandler.deliverPacket(packet);
			return;
		}

		User user = userIndex.getUser(packet.getSession());
		if (packet.getType().equals("set")){
			user.getRoster().updateRoster(packet);
			return;
		}

		if (packet.getType().equals("get")){
			logger.info("RosterHandler: get roster dump");
			packet.setType("result");
			packet.getChildren().clear();
			user.getRoster().getPacket().setParent(packet);
			MessageHandler.deliverPacket(packet);
			return;
		}

		logger.info("RosterHandler: Unknown packet" + packet.toString());
		ErrorTool.setError(packet,400,"What kind of IQ is this?");
		MessageHandler.deliverPacket(packet);
	}
}